package cn.tedu.demo.controller;

import cn.tedu.demo.common.Result;
import cn.tedu.demo.entity.User;
import cn.tedu.demo.service.UserService;
import cn.tedu.demo.vo.PageInfo;
import cn.tedu.demo.vo.SessionStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/count")
    public Result<?> count(){
        List<User> userList=userService.count();
        return Result.success(userList);
    }

    @PostMapping
    public Result<?> save(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> checkUser(@PathVariable Integer id){
        User user=userService.checkUser(id);
        return Result.success(user);

    }



    @GetMapping("/list")
    public Result<?> getByPage(PageInfo pageInfo) {
        pageInfo = userService.getByPage(pageInfo);
        return Result.success(pageInfo);
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userService.delete(id);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
         SessionStorage sessionStorage = userService.login(user);
        if (sessionStorage.getToken() == null || sessionStorage.getToken().length() == 0) {
            return Result.error("-1", "用户名或密码错误");
        }
        return Result.success(sessionStorage);
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        return userService.register(user);
    }

    @PutMapping("/update")
    public Result<?> personUpdate(@RequestBody User user){
        userService.personUpdate(user);
        return Result.success();
    }
}
